// 该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
import AboUt from "../pages/AboUt.vue";
import HoMe from "../pages/HoMe.vue";
import NeWs from "@/pages/NeWs.vue";
import MessAge from "@/pages/MessAge.vue";
import DetaIl from "@/pages/DetaIl.vue";

const router = new VueRouter({
  mode: "history",
  // 注册应用中所有的路由
  routes: [
    {
      name: "guanyu",
      path: "/about",
      component: AboUt,
      meta: { isAuth: true, title: "关于" },
    },
    {
      name: "zhuye",
      path: "/home",
      component: HoMe,
      meta: { title: "主页" },
      children: [
        {
          name: "xinwen",
          path: "news",
          component: NeWs,
          meta: { isAuth: true, title: "新闻" },
          // 独享路由守卫
          beforeEnter: (to, from, next) => {
            console.log("独享路由守卫", to, from);
            if (to.meta.isAuth) {
              //判断是否需要鉴权
              if (localStorage.getItem("school") === "atguigu") {
                next();
              } else {
                alert("学校名不对无权限查看");
              }
            } else {
              next();
            }
          },
        },

        {
          name: "xiaoxi",
          path: "message",
          component: MessAge,
          meta: { isAuth: true, title: "消息" },
          children: [
            {
              name: "xiangqing",
              path: "detail",
              component: DetaIl,
              meta: { isAuth: true, title: "详情" },
              //  props第一种写法，值为对象,该对象中的所有key-value都会以props的形式传给detail组件
              // props: { a: 1, b: "hello" },

              // props第2种写法,值为布尔值，若布尔值为真，就会把该路由组件收到的所有params参数，以props形式传给detail组件
              // props: true,

              props({ query }) {
                return { id: query.id, title: query.title };
              },
            },
          ],
        },
      ],
    },
  ],
});

// 全局前置路由守卫--初始化的时候被调用，每次路由切换之前被调用
// router.beforeEach((to, from, next) => {
//   console.log("前置路由守卫", to, from);
//   // if (to.name === "xinwen" || to.name === "xiaoxi") {
//   if (to.meta.isAuth) {
//     //判断是否需要鉴权
//     if (localStorage.getItem("school") === "atguigu") {
//       next();
//     } else {
//       alert("学校名不对无权限查看");
//     }
//   } else {
//     next();
//   }
// });

// 全局后置路由守卫--初始化的时候被调用，每次路由切换之后被调用
router.afterEach((to, from) => {
  console.log("后置路由守卫", to, from);
  document.title = to.meta.title || "atguigu";
});
export default router;
